#include "processor.hpp"

void Processor::accept(Connection & conn)
{
	LOG_STREAM_INFO << "connect from client" << LOG_EOM;
	_conn_map.insert(std::make_pair(conn.conn_id(), &conn));
}

void Processor::remove(Connection & conn)
{
	LOG_STREAM_INFO << "disconnect to client" << LOG_EOM;
	_conn_map.erase(conn.conn_id());
}

void Processor::process_input(Connection & conn, IDatagram & datagram)
{
	uint32_t type = datagram.datagram_type();

	LOG_STREAM_DEBUG << "process_input: " << datagram.to_string() << LOG_EOM;

#define CASE(class, value) \
	case value: \
	{ \
		class * d = dynamic_cast<class*>(&datagram); \
		if (NULL == d) \
		{ \
			LOG_STREAM_ERROR << "dynamic cast error. type: " << value << LOG_EOM; \
			return; \
		} \
		process(conn, *d); \
		break; \
	}

	switch (type)
	{
		CASE(DatagramTest1Req, Datagram::T_DATAGRAM_TEST1_REQ);
		default :
		{
			LOG_STREAM_ERROR << "unknown datagram type. type: " << type << LOG_EOM;
			break;
		}
	}
}

int Processor::send_datagram(IDatagram & datagram)
{
	if (_conn_map.empty())
	{
		LOG_STREAM_ERROR << "send datagram error! not connection!" << LOG_EOM;
		return -1;
	}

	LOG_STREAM_DEBUG << "send_datagram: " << datagram.to_string() << LOG_EOM;

	Connection * conn = _conn_map.begin()->second;
	conn->write(&datagram);

	return 0;
}

void Processor::process(Connection & conn, const DatagramTest1Req & req)
{
	DatagramTest1Resp resp;

	resp._times = 0x12345678;
	resp._data  = req._data;
}

